package daily.year2024.m8;

import java.util.*;

public class d24 {
    //写法1：找规律
    class Solution1 {
        //其实是找规律的题目
        public boolean closeStrings(String word1, String word2) {
            int n1 = word1.length(), n2 = word2.length();
            if(n1 != n2) {
                return false;
            }
            Map<Character,Integer> map1 = new HashMap<>(), map2 = new HashMap<>();
            char[] chars1 = word1.toCharArray(), chars2 = word2.toCharArray();
            for(int i=0;i < n1;i++) {
                map1.put(chars1[i],map1.getOrDefault(chars1[i],0) + 1);
            }
            for(int i=0;i < n2;i++) {
                map2.put(chars2[i],map2.getOrDefault(chars2[i],0) + 1);
            }
            if(!map1.keySet().equals(map2.keySet())) {
                return false;
            }
            List<Integer> l1 = new ArrayList<>(map1.values()), l2 = new ArrayList<>(map2.values());
            Collections.sort(l1);
            Collections.sort(l2);
            int size = l1.size();
            for(int i=0;i < size;i++) {
                if(!l1.get(i).equals(l2.get(i))) {
                    return false;
                }
            }
            return true;
        }
    }

    //改进写法：使用数组+判断，简练代码
    class Solution2 {
        public boolean closeStrings(String word1, String word2) {
            char[] chars1 = word1.toCharArray(), chars2 = word2.toCharArray();
            int n1 = chars1.length, n2 = chars2.length;
            if(n1 != n2) {
                return false;
            }
            int[] count1 = new int[26], count2 = new int[26];
            for(int i=0;i < n1;i++) {
                count1[chars1[i] - 'a']++;
            }
            for(int i=0;i < n2;i++) {
                count2[chars2[i] - 'a']++;
            }
            for(int i=0;i < 26;i++) {
                if(count1[i] > 0 && count2[i] == 0 || count1[i] == 0 && count2[i] > 0) {
                    return false;
                }
            }
            Arrays.sort(count1);
            Arrays.sort(count2);
            return Arrays.equals(count1, count2);
        }
    }
}
